<script setup lang="ts">
import { nextTick, reactive, ref, watch } from 'vue';
import { NButton, NInput, NInputNumber, NPopover, NSelect, NSwitch } from 'naive-ui';
import SvgIcon from '@/components/custom/svg-icon.vue';
import GoodsClassSelector from '@/components/goods/class-selector.vue';
import GoodsBrandSelector from '@/components/goods/brand-selector.vue';
import StockSelector from '@/components/stock/selector.vue';

interface SearchFilters {
  stockId: string;
  stockName: string;
  goodsName: string;
  productCode: string;
  packModel: string;
  position: string;
  searchText: string;
  brand: string;
  goodsClass: string;
  noReserveDesc: string;
  productNumber: string;
  modlePrice: boolean;
  packingUnitPrice: boolean;
  isStop: boolean;
  reservePrix: string;
  reserveNum: number | undefined;
}

interface Props {
  filters: SearchFilters;
}

interface Emits {
  (e: 'update:filters', value: SearchFilters): void;
  (e: 'search'): void;
  (e: 'reset'): void;
}

const props = defineProps<Props>();
const emit = defineEmits<Emits>();

const filterVisible = ref(false);

// 创建本地筛选条件副本
const localFilters = reactive<SearchFilters>({ ...props.filters });

// 监听props变化，同步更新本地数据
watch(
  () => props.filters,
  newFilters => {
    Object.assign(localFilters, newFilters);
  },
  { deep: true }
);

// 监听本地筛选条件变化，同步到父组件
watch(
  localFilters,
  newFilters => {
    emit('update:filters', { ...newFilters });
  },
  { deep: true }
);

const handleSearch = () => {
  emit('search');
};

const handleClassSelect = async (data: { name: string; objectId: string; selected?: string[][] }) => {
  localFilters.goodsClass = data.objectId;

  // 使用nextTick确保响应式更新完成后再发出search事件
  await nextTick();
  emit('search');
};

const handleBrandSelect = async (data: { name: string; objectId: string }) => {
  localFilters.brand = data.objectId;

  // 使用nextTick确保响应式更新完成后再发出search事件
  await nextTick();
  emit('search');
};

const handleStockSelect = async (data: { name: string; objectId: string }) => {
  localFilters.stockId = data.objectId;
  localFilters.stockName = data.name;

  // 使用nextTick确保响应式更新完成后再发出search事件
  await nextTick();
  emit('search');
};

const resetForm = () => {
  // 重置为初始值
  Object.assign(localFilters, {
    stockId: '',
    stockName: '',
    goodsName: '',
    productCode: '',
    packModel: '',
    position: '',
    searchText: '',
    brand: '',
    goodsClass: '',
    noReserveDesc: '全部',
    productNumber: '',
    modlePrice: false,
    packingUnitPrice: false,
    isStop: false,
    reservePrix: '小于',
    reserveNum: undefined
  });
  emit('reset');
  window.$message?.success('筛选条件已重置');
};

const applyFilter = () => {
  filterVisible.value = false;
  emit('search');
};
</script>

<template>
  <div class="flex items-center gap-4">
    <!-- 快速筛选 -->
    <GoodsClassSelector
      v-model="localFilters.goodsClass"
      :multiple="false"
      :clearable="true"
      :filterable="true"
      placeholder="商品分类"
      @select-class="handleClassSelect"
    />

    <GoodsBrandSelector
      v-model="localFilters.brand"
      :clearable="true"
      :filterable="true"
      placeholder="品牌"
      @select="handleBrandSelect"
    />

    <StockSelector v-model="localFilters.stockId" placeholder="仓库" @select-stock="handleStockSelect" />

    <!-- 搜索框 -->
    <NInput
      v-model:value="localFilters.searchText"
      placeholder="搜索商品名称/编号/规格"
      clearable
      class="w-200px"
      @keyup.enter="handleSearch"
    >
      <template #suffix>
        <SvgIcon icon="ant-design:search-outlined" class="h-16px w-16px cursor-pointer" @click="handleSearch" />
      </template>
    </NInput>

    <!-- 高级筛选 -->
    <NPopover v-model:show="filterVisible" placement="bottom-end" trigger="click" :style="{ minWidth: '460px' }">
      <template #trigger>
        <NButton>
          <SvgIcon icon="ant-design:filter-outlined" class="mr-1 h-14px w-14px" />
          高级筛选
        </NButton>
      </template>

      <div class="w-full">
        <!-- 标题栏 -->
        <div class="flex items-center justify-between border-b border-gray-200 bg-gray-50 px-4 py-3">
          <span class="text-gray-800 font-semibold">高级筛选</span>
          <SvgIcon icon="ant-design:filter-outlined" class="h-14px w-14px text-gray-500" />
        </div>

        <!-- 表单区域 -->
        <div class="p-4 space-y-4">
          <!-- 第一行：商品名称、商品条码 -->
          <div class="grid grid-cols-2 gap-3">
            <div class="space-y-1">
              <label class="block text-sm text-gray-700 font-medium">商品名称</label>
              <NInput v-model:value="localFilters.goodsName" placeholder="输入商品名称" />
            </div>
            <div class="space-y-1">
              <label class="block text-sm text-gray-700 font-medium">商品条码</label>
              <NInput v-model:value="localFilters.productCode" placeholder="输入商品条码" />
            </div>
          </div>

          <!-- 第二行：商品编号、商品规格 -->
          <div class="grid grid-cols-2 gap-3">
            <div class="space-y-1">
              <label class="block text-sm text-gray-700 font-medium">商品编号</label>
              <NInput v-model:value="localFilters.productNumber" placeholder="输入商品编号" />
            </div>
            <div class="space-y-1">
              <label class="block text-sm text-gray-700 font-medium">商品规格</label>
              <NInput v-model:value="localFilters.packModel" placeholder="输入商品规格" />
            </div>
          </div>

          <!-- 第三行：存放位置 -->
          <div class="space-y-1">
            <label class="block text-sm text-gray-700 font-medium">存放位置</label>
            <NInput v-model:value="localFilters.position" placeholder="输入商品存放位置" />
          </div>

          <!-- 第四行：库存数量、零库存 -->
          <div class="grid grid-cols-3 gap-3">
            <div class="col-span-2 space-y-1">
              <label class="block text-sm text-gray-700 font-medium">库存数量</label>
              <div class="flex gap-1">
                <NSelect
                  v-model:value="localFilters.reservePrix"
                  class="w-20"
                  :options="[
                    { label: '小于', value: '小于' },
                    { label: '等于', value: '等于' },
                    { label: '大于', value: '大于' }
                  ]"
                />
                <NInputNumber v-model:value="localFilters.reserveNum" placeholder="数量" class="flex-1" :min="0" />
              </div>
            </div>
            <div class="space-y-1">
              <label class="block text-sm text-gray-700 font-medium">零库存</label>
              <NSelect
                v-model:value="localFilters.noReserveDesc"
                class="w-full"
                :options="[
                  { label: '全部', value: '全部' },
                  { label: '显示', value: '显示' },
                  { label: '不显示', value: '不显示' }
                ]"
              />
            </div>
          </div>

          <!-- 第五行：开关选项 -->
          <div class="grid grid-cols-3 gap-6 pt-2">
            <div class="flex items-center justify-between">
              <label class="text-sm text-gray-700 font-medium">多规格</label>
              <NSwitch v-model:value="localFilters.modlePrice" />
            </div>
            <div class="flex items-center justify-between">
              <label class="text-sm text-gray-700 font-medium">多单位</label>
              <NSwitch v-model:value="localFilters.packingUnitPrice" />
            </div>
            <div class="flex items-center justify-between">
              <label class="text-sm text-gray-700 font-medium">停用</label>
              <NSwitch v-model:value="localFilters.isStop" />
            </div>
          </div>

          <!-- 操作按钮区域 -->
          <div class="mt-4 flex justify-end gap-3 border-t border-gray-200 pt-4">
            <NButton class="px-4 py-2" @click="resetForm">
              <SvgIcon icon="ant-design:reload-outlined" class="mr-1 h-12px w-12px" />
              重置
            </NButton>
            <NButton type="primary" class="px-4 py-2" @click="applyFilter">
              <SvgIcon icon="ant-design:search-outlined" class="mr-1 h-12px w-12px" />
              应用筛选
            </NButton>
          </div>
        </div>
      </div>
    </NPopover>
  </div>
</template>
